package com.szrt.ch04.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class LoginController extends HttpServlet {
	

	@Override
	public void init(ServletConfig config) throws ServletException {
		
		Enumeration<String> en = config.getInitParameterNames();
		
		while (en.hasMoreElements()) {
			String key =  en.nextElement();
			String value = config.getInitParameter(key);
			System.out.println(key+":"+value);
			
		}
	
	}
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

	/**
	 * post请求：
	 * 1.req.setCharacterEncoding("utf-8");
	 * set请求：
	 * 2.String ok=new String (username.getBytes("ISO-8859-1"),"utf-8");
	 * 3.过滤器
	 * 4.框架
	 * 
	 */
	req.setCharacterEncoding("utf-8");
	String username = req.getParameter("name");
	//手动装换成utf-8编码
	String ok=new String (username.getBytes("ISO-8859-1"),"utf-8");
	
	System.out.println(username);
	
	//模拟成功添加
	Map<String,String> rs=new HashMap<String,String>();
	rs.put("counter", "1");
	rs.put("消息", "添加成功");
	
	resp.setContentType("text/html;charset=utf-8");
	PrintWriter writer = resp.getWriter();
	Gson json=new Gson();
	String jsonString = json.toJson(rs);
	writer.write(jsonString);
	
	}

}
